package com.example.controller;

import com.example.dto.ApiResponse;
import com.example.dto.ChatRequest;
import com.example.dto.RenameSessionRequest;
import com.example.entity.ChatSession;
import com.example.entity.User;
import com.example.service.DeepSeekService;
import com.example.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.async.AsyncRequestTimeoutException;

import jakarta.validation.Valid;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.TimeUnit;

/**
 * DeepSeek AI助手控制器
 * 提供智能对话服务，支持上下文管理和会话功能
 */
@Slf4j
@RestController
@RequestMapping("/api/deepseek")
@RequiredArgsConstructor
@Tag(name = "DeepSeek AI助手", description = "智能对话和会话管理接口")
@PreAuthorize("hasAnyAuthority('ROLE_USER', 'ROLE_TEACHER', 'ROLE_ADMIN')")
public class DeepSeekController {

    private final DeepSeekService deepSeekService;
    private final UserService userService;

    /**
     * 简单对话接口（无上下文）
     * 兼容原有接口，适用于单次问答
     */
    @PostMapping("/chat")
    @Operation(summary = "简单对话", description = "发送单条消息给AI助手，不保存对话历史")
    public ResponseEntity<String> chat(
            @Parameter(description = "用户消息", required = true)
            @RequestBody String message) {
        try {
            String response = deepSeekService.chat(message).get(60, TimeUnit.SECONDS);
            log.info("简单对话完成 (回复长度 {})", response.length());
            return ResponseEntity.ok(response);
        } catch (TimeoutException e) {
            log.error("简单对话请求超时", e);
            return ResponseEntity.status(503).body("请求超时，请稍后重试");
        } catch (InterruptedException e) {
            log.error("简单对话请求被中断", e);
            Thread.currentThread().interrupt();
            return ResponseEntity.status(500).body("请求处理被中断");
        } catch (ExecutionException e) {
            log.error("简单对话执行错误", e.getCause());
            Throwable cause = e.getCause();
            if (cause instanceof TimeoutException) {
                return ResponseEntity.status(503).body("请求超时，请稍后重试");
            }
            return ResponseEntity.status(500).body("处理请求时发生错误: " + (cause != null ? cause.getMessage() : e.getMessage()));
        } catch (Exception e) {
            log.error("简单对话未知错误", e);
            return ResponseEntity.status(500).body("处理请求时发生未知错误");
        }
    }

    /**
     * 带上下文的对话接口
     * 支持会话记忆，可以延续之前的对话
     */
    @PostMapping("/chat-with-context")
    @Operation(summary = "上下文对话", description = "发送消息给AI助手，保持对话上下文")
    public ResponseEntity<ApiResponse<ChatContextResponse>> chatWithContext(
            @Valid @RequestBody ChatRequest request) {
        try {
            User user = getCurrentUser();
            String response = deepSeekService.chatWithContext(
                    user.getId(), 
                    request.getSessionId(), 
                    request.getMessage()
            ).get(60, TimeUnit.SECONDS);
            
            // 获取更新后的会话信息
            ChatSession session;
            if (request.getSessionId() == null || request.getSessionId().isEmpty()) {
                session = deepSeekService.getUserSessions(user.getId()).stream()
                        .filter(s -> "ACTIVE".equals(s.getStatus()))
                        .findFirst()
                        .orElse(null);
            } else {
                session = deepSeekService.getSessionDetail(user.getId(), request.getSessionId());
            }
            
            ChatContextResponse contextResponse = new ChatContextResponse();
            contextResponse.setResponse(response);
            contextResponse.setSessionId(session != null ? session.getSessionId() : null);
            contextResponse.setSessionTitle(session != null ? session.getTitle() : null);
            
            return ResponseEntity.ok(ApiResponse.success("对话成功", contextResponse));
            
        } catch (TimeoutException e) {
            log.error("上下文对话请求超时", e);
            return ResponseEntity.status(503).body(ApiResponse.error("请求超时，请稍后重试"));
        } catch (Exception e) {
            log.error("上下文对话处理失败", e);
            return ResponseEntity.status(500).body(ApiResponse.error("对话处理失败: " + e.getMessage()));
        }
    }

    /**
     * 创建新的对话会话
     */
    @PostMapping("/sessions")
    @Operation(summary = "创建新会话", description = "创建一个新的对话会话")
    public ResponseEntity<ApiResponse<ChatSession>> createSession(
            @RequestBody(required = false) CreateSessionRequest request) {
        try {
            User user = getCurrentUser();
            String initialMessage = request != null ? request.getInitialMessage() : null;
            
            ChatSession session = deepSeekService.createNewSession(user.getId(), initialMessage);
            return ResponseEntity.ok(ApiResponse.success("会话创建成功", session));
            
        } catch (Exception e) {
            log.error("创建会话失败", e);
            return ResponseEntity.status(500).body(ApiResponse.error("创建会话失败: " + e.getMessage()));
        }
    }

    /**
     * 获取用户的所有会话列表
     */
    @GetMapping("/sessions")
    @Operation(summary = "获取会话列表", description = "获取当前用户的所有对话会话")
    public ResponseEntity<ApiResponse<List<ChatSession>>> getUserSessions() {
        try {
            User user = getCurrentUser();
            List<ChatSession> sessions = deepSeekService.getUserSessions(user.getId());
            return ResponseEntity.ok(ApiResponse.success("获取会话列表成功", sessions));
            
        } catch (Exception e) {
            log.error("获取会话列表失败", e);
            return ResponseEntity.status(500).body(ApiResponse.error("获取会话列表失败: " + e.getMessage()));
        }
    }

    /**
     * 获取指定会话的详情
     */
    @GetMapping("/sessions/{sessionId}")
    @Operation(summary = "获取会话详情", description = "获取指定会话的详细信息和对话历史")
    public ResponseEntity<ApiResponse<ChatSession>> getSessionDetail(
            @Parameter(description = "会话ID", required = true)
            @PathVariable String sessionId) {
        try {
            User user = getCurrentUser();
            ChatSession session = deepSeekService.getSessionDetail(user.getId(), sessionId);
            return ResponseEntity.ok(ApiResponse.success("获取会话详情成功", session));
            
        } catch (Exception e) {
            log.error("获取会话详情失败", e);
            return ResponseEntity.status(404).body(ApiResponse.error("会话不存在或已过期"));
        }
    }

    /**
     * 重命名会话
     */
    @PutMapping("/sessions/{sessionId}/title")
    @Operation(summary = "重命名会话", description = "修改会话的标题")
    public ResponseEntity<ApiResponse<String>> renameSession(
            @Parameter(description = "会话ID", required = true)
            @PathVariable String sessionId,
            @Valid @RequestBody RenameSessionRequest request) {
        try {
            User user = getCurrentUser();
            
            // 添加详细的调试日志
            log.info("收到重命名会话请求 - 用户: {}, 会话ID: {}, 请求体: {}", 
                    user.getId(), sessionId, request);
            log.info("请求中的newTitle值: '{}', 是否为null: {}, 是否为空字符串: {}", 
                    request.getNewTitle(), 
                    request.getNewTitle() == null,
                    request.getNewTitle() != null && request.getNewTitle().isEmpty());
            
            // 验证新标题不为空（虽然已有@Valid验证，但这里再次确认）
            if (request.getNewTitle() == null || request.getNewTitle().trim().isEmpty()) {
                log.warn("重命名会话失败：新标题为空 - 用户: {}, 会话ID: {}", user.getId(), sessionId);
                return ResponseEntity.badRequest().body(ApiResponse.error("会话标题不能为空"));
            }
            
            String trimmedTitle = request.getNewTitle().trim();
            boolean success = deepSeekService.renameSession(user.getId(), sessionId, trimmedTitle);
            
            if (success) {
                log.info("会话重命名成功 - 用户: {}, 会话ID: {}, 新标题: '{}'", 
                        user.getId(), sessionId, trimmedTitle);
                return ResponseEntity.ok(ApiResponse.success("会话重命名成功", null));
            } else {
                log.warn("会话重命名失败：会话不存在 - 用户: {}, 会话ID: {}", user.getId(), sessionId);
                return ResponseEntity.status(404).body(ApiResponse.error("会话不存在或重命名失败"));
            }
            
        } catch (Exception e) {
            log.error("重命名会话失败 - 会话ID: {}, 错误: {}", sessionId, e.getMessage(), e);
            return ResponseEntity.status(500).body(ApiResponse.error("重命名会话失败: " + e.getMessage()));
        }
    }

    /**
     * 删除会话
     */
    @DeleteMapping("/sessions/{sessionId}")
    @Operation(summary = "删除会话", description = "删除指定的对话会话")
    public ResponseEntity<ApiResponse<String>> deleteSession(
            @Parameter(description = "会话ID", required = true)
            @PathVariable String sessionId) {
        try {
            User user = getCurrentUser();
            boolean success = deepSeekService.deleteSession(user.getId(), sessionId);
            
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("会话删除成功", null));
            } else {
                return ResponseEntity.status(404).body(ApiResponse.error("会话不存在或删除失败"));
            }
            
        } catch (Exception e) {
            log.error("删除会话失败", e);
            return ResponseEntity.status(500).body(ApiResponse.error("删除会话失败: " + e.getMessage()));
        }
    }

    /**
     * 归档会话
     */
    @PutMapping("/sessions/{sessionId}/archive")
    @Operation(summary = "归档会话", description = "将会话标记为已归档状态")
    public ResponseEntity<ApiResponse<String>> archiveSession(
            @Parameter(description = "会话ID", required = true)
            @PathVariable String sessionId) {
        try {
            User user = getCurrentUser();
            boolean success = deepSeekService.archiveSession(user.getId(), sessionId);
            
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("会话归档成功", null));
            } else {
                return ResponseEntity.status(404).body(ApiResponse.error("会话不存在或归档失败"));
            }
            
        } catch (Exception e) {
            log.error("归档会话失败", e);
            return ResponseEntity.status(500).body(ApiResponse.error("归档会话失败: " + e.getMessage()));
        }
    }

    /**
     * 更新会话配置
     */
    @PutMapping("/sessions/{sessionId}/config")
    @Operation(summary = "更新会话配置", description = "更新会话的配置参数")
    public ResponseEntity<ApiResponse<String>> updateSessionConfig(
            @Parameter(description = "会话ID", required = true)
            @PathVariable String sessionId,
            @Valid @RequestBody ChatSession.SessionConfig config) {
        try {
            User user = getCurrentUser();
            boolean success = deepSeekService.updateSessionConfig(user.getId(), sessionId, config);
            
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("会话配置更新成功", null));
            } else {
                return ResponseEntity.status(404).body(ApiResponse.error("会话不存在或配置更新失败"));
            }
            
        } catch (Exception e) {
            log.error("更新会话配置失败", e);
            return ResponseEntity.status(500).body(ApiResponse.error("更新会话配置失败: " + e.getMessage()));
        }
    }

    /**
     * 异常处理
     */
    @ExceptionHandler(AsyncRequestTimeoutException.class)
    public ResponseEntity<ApiResponse<String>> handleAsyncRequestTimeoutException(AsyncRequestTimeoutException e) {
        log.warn("异步请求超时", e);
        return ResponseEntity.status(503).body(ApiResponse.error("请求超时，请稍后重试"));
    }

    /**
     * 处理验证错误
     */
    @ExceptionHandler(org.springframework.web.bind.MethodArgumentNotValidException.class)
    public ResponseEntity<ApiResponse<String>> handleValidationException(
            org.springframework.web.bind.MethodArgumentNotValidException e) {
        
        StringBuilder errorMessage = new StringBuilder("参数验证失败：");
        e.getBindingResult().getFieldErrors().forEach(error -> {
            errorMessage.append(error.getField())
                       .append(" - ")
                       .append(error.getDefaultMessage())
                       .append("; ");
        });
        
        log.warn("参数验证失败: {}", errorMessage.toString());
        return ResponseEntity.badRequest().body(ApiResponse.error(errorMessage.toString()));
    }

    /**
     * 获取当前用户信息
     */
    private User getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String username = authentication.getName();
        return userService.getUserByUsername(username);
    }

    // DTO类定义
    public static class ChatContextResponse {
        private String response;
        private String sessionId;
        private String sessionTitle;

        public String getResponse() { return response; }
        public void setResponse(String response) { this.response = response; }
        public String getSessionId() { return sessionId; }
        public void setSessionId(String sessionId) { this.sessionId = sessionId; }
        public String getSessionTitle() { return sessionTitle; }
        public void setSessionTitle(String sessionTitle) { this.sessionTitle = sessionTitle; }
    }

    public static class CreateSessionRequest {
        private String initialMessage;

        public String getInitialMessage() { return initialMessage; }
        public void setInitialMessage(String initialMessage) { this.initialMessage = initialMessage; }
    }
} 